package org.llc.flink.study.example

object List08 {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 4, 5)

    /** (((1-2) - 3) - 4) - 5 = -13
      * 1 - 2 = -1
      * -1 - 3 = -4
      * -4 - 4 = -8
      * -8 - 5 = -13
      */
    println(list.reduceLeft(minus))

    /** 1 - (2 - (3 -(4 - 5))) = 3
      * 4 - 5 = -1
      * 3 - -1 = 4
      * 2 - 4 = -2
      * 1 - -2 = 3
      */
    println(list.reduceRight(minus))

    // reduce等价于 reduceLeft
    println(list.reduce(minus))

    // 求list中的最小值 1
    println(list.reduce(min))

  }

  def minus(n1: Int, n2: Int): Int = {
    println(s"$n1 - $n2 = ${n1 - n2}")
    n1 - n2
  }

  def min(n1: Int, n2: Int): Int = {
    if (n1 > n2) {
      n2
    } else {
      n1
    }
  }
}
